package com.malbbmsomanager.retailmanagement;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.malbbmsomanager.transactions.DM_BBM_InvoiceSalesOrder;
import com.malbbmsomanagerdemo.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class DM_BBM_RetOutstanding_Information extends Activity {
	private String DBNAME = "dminvoicemanagerbbm.db";
	TextView txtHeading;
	private static final String TAG = null;
	SQLiteDatabase mydb;
	String TagIdRetailer,TxnDate;
	String TagId,TagMain;
	SimpleDateFormat originalFormat = new SimpleDateFormat("dd MM yyyy");
	SimpleDateFormat targetFormat = new SimpleDateFormat("dd/MM/yyyy");
	static SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
	Date settingDate;
	static Integer daysCount;

	public void btnBack(View view) {
		if(TagMain.equals("SO")){
			Intent myIntent = new Intent(view.getContext(),
					DM_BBM_InvoiceSalesOrder.class);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			finish();
		}
		else{
			Intent myIntent = new Intent(view.getContext(),
					DM_BBM_Retailer_Master.class);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			finish();
		}
		
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_retoutstanding_information);
		
		
		TextView txtHeading = (TextView) findViewById(R.id.txtHeading);
		txtHeading.setText("Retailer Outstanding");
		
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			TagId = bundle.getString("TAGID");
			String[] ToLocDetails = TagId.split("/");
			TagMain = ToLocDetails[0]; // fromLocCode
			TagIdRetailer = ToLocDetails[1]; // fromLocName
		}
	
		callCurrentRetailer();
		try {
			DisplayRetailerList();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private void callCurrentRetailer() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curCurrentRetailer = null;
		try {
			String query = "SELECT * from FRetailScrSum";
			curCurrentRetailer = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (curCurrentRetailer != null) {
			if (curCurrentRetailer.getCount() > 0) {
				while (curCurrentRetailer.moveToNext()) {
					TagIdRetailer = curCurrentRetailer.getString(1);
				}
			}
		}

	}
	
	private void DisplayRetailerList() throws ParseException {
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dmretaileroutstandlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2", "coldes_3", "coldes_4" };
		int[] totrdes = new int[] { R.id.retoutreference, R.id.retoutdate,
				R.id.retoutamount, R.id.retoutamountage };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curListRetailer = null;
		try {
			String query = "SELECT RefNo,TxnDate,Totbal,DebCode FROM fddbnote WHERE DebCode = '" + TagIdRetailer + "'";
			curListRetailer = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (curListRetailer != null) {
			if (curListRetailer.getCount() > 0) {
				while (curListRetailer.moveToNext()) {
					String strRefNo = curListRetailer.getString(0);
					String strTxnDate = curListRetailer.getString(1);
					String Totbal = curListRetailer.getString(2);
					
					String[] record_2Array = strTxnDate.split(" ");
					strTxnDate = record_2Array[0]; // this will contain Date Part
					String[] record_3Array = strTxnDate.split("/");
					String month = record_3Array[0];
					String day = record_3Array[1];
					String Year = record_3Array[2];
					
					if(month.length()==1){
						month = "0" + month;
					}
					else if(day.length()==1){
						day = "0" + day;
					}
					strTxnDate = day +"/"+month+"/"+Year;
					try {
						settingDate = originalFormat.parse(strTxnDate.replaceAll(
								"[-+/.^:,]", " "));
						TxnDate = targetFormat.format(settingDate);
					} catch (ParseException ex) {
						Log.v(TAG, "Exception ****** :" + ex);
						TxnDate = getDeviceTaxnDate().toString();
					}
				
					int fromYear = Integer.parseInt(Year);
					int fromMonth = Integer.parseInt(month);
					int fromDay = Integer.parseInt(day);
					
					String CurrentDate = getDeviceTaxnDate().toString();
					String[] CurDayArray = CurrentDate.split("/");
					int toDay = Integer.parseInt(CurDayArray[0]);
					int toMonth = Integer.parseInt(CurDayArray[1]);
					int toYear = Integer.parseInt(CurDayArray[2]);
					
					//Calculate Days
					 Calendar c1=Calendar.getInstance();  
				     c1.set(fromYear,fromMonth,fromDay);  
				     Calendar c2=Calendar.getInstance();  
				     c2.set(toYear,toMonth,toDay);  
				  
				     Date d1=c1.getTime();  
				     Date d2=c2.getTime();  
				  
				     long diff=d2.getTime()-d1.getTime();  
				     int noofdays=(int)(diff/(1000*24*60*60));  
				     Log.v(TAG, "DAYS :" + noofdays);
					
					
					
					BigDecimal StrTotalTax = new BigDecimal(Totbal.replaceAll("[,]", ""));
					StrTotalTax = StrTotalTax.setScale(2,
							BigDecimal.ROUND_HALF_DOWN);
					
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", strRefNo);
					maptrdes.put("coldes_2", TxnDate);
					maptrdes.put("coldes_3", "" + StrTotalTax);
					maptrdes.put("coldes_4", "" + noofdays);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes,
						R.layout.dm_bbm_retoutstanding_information_raw, fromtrdes,
						totrdes);
				lvtypedes.setAdapter(adaptertrdes);
			}
		}
		curListRetailer.close();
		mydb.close();

	}
	private static void printOutput(String type, Date d1, Date d2, long result) {
		  System.out.println(type+ "- Days between: " + sdf.format(d1)
		                    + " and " + sdf.format(d2) + " is: " + result);
		  daysCount = (int) (long) result;
		   
		}
	public static long calculateDays(Date dateEarly, Date dateLater) {
		  return (dateLater.getTime() - dateEarly.getTime()) / (24 * 60 * 60 * 1000);
		}
	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}
	private String getDeviceTaxnDate() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("dd/MM/yyyy");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}
}
